// pages/dev/storage/index.js
const storageManager = require('../../../manager/storageManager').getInstance();

Page({
  data: {
    userInfoStr: '',
    learningDataStr: '',
    todayTaskExtraStr: '',
    learningUnitsStr: ''
  },

  onShow() {
    this.refresh()
  },

  initData() {
    const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
    const userInfo = { avatarUrl: defaultAvatarUrl, nickName: '小冒险家' }
    const learningData = { level: 1, progress: 30, completedWords: 3, reviewCount: 7 }
    const todayTaskExtra = { totalWords: 10, rewardCoins: 50 }
    const learningUnits = [
      { id: 1, name: '动物世界', emoji: '🐯', color: '#FF9AA2', progress: 75, locked: false },
      { id: 2, name: '食物乐园', emoji: '🍎', color: '#FFB7B2', progress: 40, locked: false },
      { id: 3, name: '学校生活', emoji: '📚', color: '#FFDAC1', progress: 20, locked: false },
      { id: 4, name: '家庭成员', emoji: '👨‍👩‍👧‍👦', color: '#E2F0CB', progress: 0, locked: false },
      { id: 5, name: '交通工具', emoji: '🚗', color: '#B5EAD7', progress: 0, locked: true },
      { id: 6, name: '自然环境', emoji: '🌳', color: '#C7CEEA', progress: 0, locked: true }
    ]

    storageManager.setStorage(storageManager.STORAGE_KEYS.USER_INFO, userInfo)
    storageManager.setStorage(storageManager.STORAGE_KEYS.LEARNING_DATA, learningData)
    storageManager.setStorage(storageManager.STORAGE_KEYS.TODAY_TASK_EXTRA, todayTaskExtra)
    storageManager.setStorage(storageManager.STORAGE_KEYS.LEARNING_UNITS, learningUnits)

    wx.showToast({ title: '已写入示例数据', icon: 'success' })
    this.refresh()
  },

  clearData() {
    ;['userInfo', 'learningData', 'todayTaskExtra', 'learningUnits'].forEach(k => storageManager.removeStorage(k))
    wx.showToast({ title: '已清空', icon: 'none' })
    this.refresh()
  },

  refresh() {
    const userInfo = storageManager.getStorage(storageManager.STORAGE_KEYS.USER_INFO)
    const learningData = storageManager.getStorage(storageManager.STORAGE_KEYS.LEARNING_DATA)
    const todayTaskExtra = storageManager.getStorage(storageManager.STORAGE_KEYS.TODAY_TASK_EXTRA)
    const learningUnits = storageManager.getStorage(storageManager.STORAGE_KEYS.LEARNING_UNITS)

    this.setData({
      userInfoStr: this.pretty(userInfo),
      learningDataStr: this.pretty(learningData),
      todayTaskExtraStr: this.pretty(todayTaskExtra),
      learningUnitsStr: this.pretty(learningUnits)
    })
  },

  pretty(obj) {
    try {
      return obj ? JSON.stringify(obj, null, 2) : '(empty)'
    } catch (e) {
      return String(obj)
    }
  },
  
  // 转发给朋友
  onShareAppMessage: function() {
    return {
      title: '拾刻学习 - 数据存储管理',
      path: '/pages/dev/storage/index',
      // imageUrl: '/images/setting.png'
    };
  },
  
  // 分享到朋友圈
  onShareTimeline: function() {
    return {
      title: '拾刻学习 - 数据存储管理',
      query: 'from=timeline',
      // imageUrl: '/images/setting.png'
    };
  }
})
